package com.voice.server.map;

import com.voice.server.entity.DevicePinYinCode;
import com.voice.server.repository.DevicePinYinCodeRepository;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
public class PinYinCodeMap implements InitializingBean {

    @Autowired
    private DevicePinYinCodeRepository devicePinYinCodeRepository;
    private Map<String, List<DevicePinYinCode>> map = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        List<DevicePinYinCode> list = devicePinYinCodeRepository.findAll();
        map = list.stream().collect(Collectors.groupingBy(DevicePinYinCode::getDeviceKey));
    }

    public List<DevicePinYinCode> get(String deviceKey){
        return map.get(deviceKey);
    }

    public void add(DevicePinYinCode devicePinYinCode){
        List<DevicePinYinCode> list= map.get(devicePinYinCode.getDeviceKey());
        list.add(devicePinYinCode);
    }

    public void update(DevicePinYinCode devicePinYinCode,int code){
        List<DevicePinYinCode> list= map.get(devicePinYinCode.getDeviceKey());
        for(DevicePinYinCode devicePinYinCode1:list){
            if(devicePinYinCode1.getPinyin().equals(devicePinYinCode.getPinyin())){
                devicePinYinCode1.setCode(code);
                return;
            }
        }
    }
}
